package com.wuseguang.springcloud.timer;


import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.JdbcTemplate.HaiweidaCooperativeSchoolJdbc;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.repository.*;
import com.wuseguang.springcloud.entity.*;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.HaiweidaUtil;
import com.wuseguang.springcloud.util.WeChat.TemplateTools;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.StringUtils;

import java.lang.reflect.Array;
import java.util.*;

public class HaiweidaCooperativeSchoolTimer extends QuartzJobBean {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private HaiweidaCooperativeSchoolRepository haiweidaCooperativeSchoolRepository;
    @Autowired
    private HaiweidaCooperativeSchoolJdbc haiweidaCooperativeSchoolJdbc;
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private ImportAndExportSchoolsRepository importAndExportSchoolsRepository;
    @Autowired
    private WXJdbc wXJdbc;
    @Autowired
    private TemperatureRepository temperatureRepository;
    @Autowired
    private HaiweidaLogRepository haiweidaLogRepository;
    @Autowired
    private HaiweidaDataIdRepository haiweidaDataIdRepository;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        Date date2 =new Date();
        logger.info("海威达任务开始执行");

        //获取海威达合作学校
        List<HaiweidaCooperativeSchool> list = haiweidaCooperativeSchoolRepository.findAll();
        logger.info("学校集合:"+list.toString());
        //循环海威达合作学校
        for (HaiweidaCooperativeSchool h : list) {
            logger.info("学校id:"+h.getSchoolId());
            //如果token为空，或者token有效时间小于当前时间获取新的token
            if (StringUtils.isEmpty(h.getToken())) {
                logger.info("token为空需要等于获取token");
                //获取token
                Map<String, Object> map = HaiweidaUtil.login(h.getSchoolCode(), h.getUserName(), h.getPassword());
                //有效时间的时间戳
                Long time = (System.currentTimeMillis() + (Integer.valueOf(map.get("expTime").toString()) * 1000) - 60000);
                Date d = new Date(time);
                h.setExpTime(DateUtil.strToDateLong(DateUtil.dateToString(d, "yyyy-MM-dd hh:mm:ss"), "yyyy-MM-dd hh:mm:ss"));
                h.setToken("JWT " + map.get("token").toString());
                h.setUuid(map.get("uuid").toString());
                haiweidaCooperativeSchoolRepository.save(h);
            } else if (h.getExpTime().getTime() < System.currentTimeMillis()) {
                logger.info("token已过期用过期token获取新token");
                //获取token
                Map<String, Object> map = HaiweidaUtil.login(h.getSchoolCode(), h.getUserName(), h.getPassword());
                //有效时间的时间戳
                Long time = (System.currentTimeMillis() + (Integer.valueOf(map.get("expTime").toString()) * 1000) - 60000);
                Date d = new Date(time);
                h.setExpTime(DateUtil.strToDateLong(DateUtil.dateToString(d, "yyyy-MM-dd hh:mm:ss"), "yyyy-MM-dd hh:mm:ss"));
                h.setToken("JWT " + map.get("token").toString());
                h.setUuid(map.get("uuid").toString());
                haiweidaCooperativeSchoolRepository.save(h);
            }

            //获取id
            HaiweidaDataId haiweidaDataId = haiweidaDataIdRepository.findBySchoolId(h.getSchoolId());

            //进出校集合
            List<Map<String, Object>> inOutList = HaiweidaUtil.haiweidaInAndOutOfSchool(h.getToken(),haiweidaDataId.getHaiweidaMinId());
            if (inOutList!=null&&inOutList.size()>0){
                //修改id,下次获取
                haiweidaDataId.setHaiweidaMinId(Integer.valueOf(inOutList.get(inOutList.size()-1).get("id").toString())+1);
                haiweidaDataIdRepository.save(haiweidaDataId);
            }


           //海威达日志
            HaiweidaLog log = new HaiweidaLog();
            log.setAddTime(date2);
            log.setDates(inOutList.toString());
            log.setSchoolId(h.getSchoolId());
            haiweidaLogRepository.save(log);

            /*if (inOutList!=null&&inOutList.get(0)!=null){//token 失效无法登陆
                if (inOutList.get(0).get("code")!=null){
                    //获取token
                    Map<String, Object> map = HaiweidaUtil.login(h.getSchoolCode(), h.getUserName(), h.getPassword());
                    //有效时间的时间戳
                    Long time = (System.currentTimeMillis() + (Integer.valueOf(map.get("expTime").toString()) * 1000) - 60000);
                    Date d = new Date(time);
                    h.setExpTime(DateUtil.strToDateLong(DateUtil.dateToString(d, "yyyy-MM-dd hh:mm:ss"), "yyyy-MM-dd hh:mm:ss"));
                    h.setToken("JWT " + map.get("token").toString());
                    h.setUuid(map.get("uuid").toString());
                    haiweidaCooperativeSchoolRepository.save(h);

                }
            }*/



            //循环进出校集合
            for (Map<String, Object> map : inOutList) {
                logger.info("循环进出校集合");
                //用户id
                String userId = (String) map.get("userId");
                //判断用户id是否为空
                if (StringUtils.isEmpty(userId)) {
                    continue;
                }
                //进出校时间
                Date date = DateUtil.strToDateLong(map.get("time").toString(), "yyyy-MM-dd HH:mm:ss");
                //进出状态(in进out出) 0进校，1出校
                Integer type = "in".equals(map.get("inout").toString()) ? 0 : 1;
                //用户类型（teacher/student）
                String userType = map.get("userType").toString();
                //温度
                String temperature = map.get("temperature").toString();
                //异常体温
                Double yi = 37.3;
                //正常
                Integer actual = 0;
                if (!StringUtils.isEmpty(temperature)) {
                    actual = Double.valueOf(temperature) >= yi ? 1 : 0;
                }


                Integer count = importAndExportSchoolsRepository.findByDate(Integer.valueOf(userId), type, date);
                //如果这个时间段有相同的数据就不执行以下操作
                if (count > 0) {
                    continue;
                }
                //判断是否为学生
                if ("student".equals(userType)) {

                    //学生进出记录
                    ImportAndExportSchools iaes = new ImportAndExportSchools();
                    //根据卡号查询学生信息
                    Student student = studentRepository.findById(Integer.valueOf(userId)).get();

                    //添加进出记录
                    iaes.setStudentId(student.getId());
                    iaes.setType(type);
                    iaes.setTime(date);
                    importAndExportSchoolsRepository.save(iaes);
                    //推送信息到公众号
                    officialAccountPush(student, type.toString(), StringUtils.isEmpty(temperature) ? "0" : temperature,date);
                    //温度实际
                    if (actual == 1) {
                        logger.info("学生体温异常推送给班主任");
                        officialAccountPushTeacher(student.getClassId(), temperature, student.getStudentName(), date);
                    }

                    try {
                        //学生体温
                        Temperature t = new Temperature();
                        t.setAddTime(new Date());
                        t.setClassId(student.getClassId());
                        t.setMonitoringTime(date);
                        t.setStudentId(student.getId());
                        t.setTiWen(StringUtils.isEmpty(temperature) ? 0 : Double.valueOf(temperature));
                        t.setState(actual);
                        temperatureRepository.save(t);
                    } catch (Exception e) {
                        logger.info("体温添加失败");
                    }
                }
            }

        }
    }

    /**
     * 学生进离校公众号推送
     *
     * @param student     学生信息
     * @param type        0进校，离校
     * @param temperature 温度
     */
    public void officialAccountPush(Student student, String type, String temperature, Date date) {

        //获取token
        String accessToken = wXJdbc.getOfficialAccountAccessToken(0);

        //查询家长的小程序openId
        String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";

        //家长openid
        Map<String, Object> parent = haiweidaCooperativeSchoolJdbc.queryMap(sql, student.getId());
        //获取公众号的openid
        String openId = (String) parent.get("open_id_two");
        //判断openid是否为空
        if (!StringUtils.isEmpty(openId)) {

            //查询班级名称
            sql = "select `name` string from classes where id = ?";
            String className = haiweidaCooperativeSchoolJdbc.queryString(sql, student.getClassId());


            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("first", "家长您好，您的孩子有一条新的进出校信息。");
            pushMap.put("keyword1", student.getStudentName());
            pushMap.put("keyword2", "0".equals(type) ? "进校" : "离校");
            pushMap.put("keyword3", DateUtil.parseData(date,"yyyy-MM-dd HH:mm:ss"));
            pushMap.put("remark", "0".equals(temperature) ? "感谢您的支持" : "学生体温:" + temperature);

            //跳转小程序信息
            JSONObject appletJson = new JSONObject();
            appletJson.put("appid", "wx30b606bac7775eba");
            appletJson.put("pagepath", "pages/leavingSchool/checkStu?class_name=" + className);

            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //推送公众号信息
            WXUtil.officialAccountPush(accessToken, openId, "Gm7b6gou5IEdsViu6CLxi46zHRvGUuuljQiVWlKbSZs", "", appletJson, json);
        }
    }

    /**
     * 推送体温异常的学生
     *
     * @param classId 班级id
     * @param tiwen   体温
     */
    public void officialAccountPushTeacher(Integer classId, String tiwen, String stuName, Date date) {

        //获取token
        String accessToken = wXJdbc.getOfficialAccountAccessToken(0);
        //查询班主任的token
        String sql = "select open_id_two string from teacher t right join classes c on(t.id=c.class_teacher_id) where c.id =?";
        String openId = haiweidaCooperativeSchoolJdbc.queryString(sql, classId);
        //token不为空推送
        if (!StringUtils.isEmpty(openId)) {

            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("first", "尊敬的老师，您有一个学生体温异常");
            pushMap.put("keyword1", stuName);
            pushMap.put("keyword2", tiwen);
            pushMap.put("keyword3", date);
            pushMap.put("remark", "感谢您的支持");

            //跳转小程序信息
        /*JSONObject appletJson = new JSONObject();
        appletJson.put("appid", "wx30b606bac7775eba");
        appletJson.put("pagepath", "pages/leavingSchool/checkStu?class_name=" + className);*/

            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //推送公众号信息
            WXUtil.officialAccountPush(accessToken, openId, "dNEqc2S7OQMQh2s9tZe_hMSKsrkd6HgHYZQVKX-n_rw", "", null, json);
        }

    }
}
